package org.xplugin.demo.module2;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Process;
import android.view.View;
import android.widget.TextView;

import com.google.android.material.snackbar.Snackbar;
import com.hase.ag35.remotekey.key.KeyManager;
import com.hase.ag35.remotekey.key.ui.KeyDialogFragment;
import com.hase.ag35.remotekey.key.ui.KeyShareKeyFragment;
import com.hase.ag35.remotekey.key.ui.KeyVehicleInfoActivity;
import com.hase.ag35.remotekey.key.wrapper.NormalCallbackWrapper;
import com.hase.ag35.remotekey.key.wrapper.StatusCallBackWrapper;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.uber.autodispose.AutoDispose;
import com.uber.autodispose.android.lifecycle.AndroidLifecycleScopeProvider;

import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Lifecycle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mine_bt_key_item);
        findWidgets();
        go();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseDigitalKey();
    }

    private void go() {
        Looper.myQueue().addIdleHandler(() -> {
            if (checkKeyPermission())
                initDigitalKey();
            else requestP();
            return false;
        });
    }

    private void requestP() {
        new RxPermissions(this)
                .requestEachCombined(
                        Manifest.permission.READ_PHONE_STATE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_FINE_LOCATION
                )
                .as(AutoDispose.autoDisposable(AndroidLifecycleScopeProvider.from(
                        this, Lifecycle.Event.ON_DESTROY
                )))
                .subscribe(request -> {
                    if (request.granted) initDigitalKey();
                    else if (request.shouldShowRequestPermissionRationale)
                        showMsg("您已拒绝权限");
                    else showMsg("您已拒绝权限");
                });
    }

    private boolean checkKeyPermission() {
        int phoneP = getPackageManager().checkPermission(
                Manifest.permission.READ_PHONE_STATE, getPackageName()
        );
        int storageP = getPackageManager().checkPermission(
                Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()
        );
        int locP = getPackageManager().checkPermission(
                Manifest.permission.ACCESS_FINE_LOCATION, getPackageName()
        );
        return phoneP == PackageManager.PERMISSION_GRANTED
                && storageP == PackageManager.PERMISSION_GRANTED
                && locP == PackageManager.PERMISSION_GRANTED;
    }

    private NormalCallbackWrapper findCarNormalCBWrapper;
    private void findWidgets() {
        rootView = getWindow().getDecorView();
        View root = findViewById(R.id.bt_root);
        txtShare = findViewById(R.id.bt_key_share);
        txtOwner = findViewById(R.id.bt_car_owner);
        txtFind = findViewById(R.id.bt_find_car);
        txtKey = findViewById(R.id.bt_key);
        txtState = findViewById(R.id.bt_state);

        txtShare.setOnClickListener(
                v -> KeyShareKeyFragment.newInstance()
                        .show(getSupportFragmentManager(), "KeyShareKeyFragment")
        );
        if (findCarNormalCBWrapper == null)
            findCarNormalCBWrapper = new NormalCallbackWrapper(new KeyManager.NormalCallback() {
                @Override
                public void onSuccess() {
                    showMsg("发送成功");
                }
                @Override
                public void onFail(String errorMsg) { }
            });
        txtFind.setOnClickListener(v -> KeyManager.controlCar(8, findCarNormalCBWrapper));
        txtKey.setOnClickListener(
                v -> KeyDialogFragment.newInstance()
                        .show(getSupportFragmentManager(), "KeyDialogFragment"));
        root.setOnClickListener(v -> {
            if (isMaster) {
                if (keyState != STATE_INVALID
                        && keyState != STATE_UNINITIALIZED
                        && keyState != STATE_INITIALIZING)
                    startActivity(new Intent(this, KeyVehicleInfoActivity.class));
            } else if (keyState == STATE_CONNECTED)
                startActivity(new Intent(this, KeyVehicleInfoActivity.class));
            else
                showMsg("请先连接车辆");
        });
    }

    private static final int STATE_INVALID       = -1;
    private static final int STATE_INITIALIZING  = 11;
    private static final int STATE_UNINITIALIZED = 0;
    private static final int STATE_ACTIVATED     = 2;
    private static final int STATE_CONNECTED     = 3;
    private int keyState = STATE_INVALID;
    private String phone = "17368062082";
    private TextView txtShare, txtOwner, txtFind, txtKey, txtState;
    private View rootView;
    private boolean isMaster;
    private void onKeyStateChanged(int state) {
        rootView.post(() -> {
            keyState = state;
            dismissLoading();
            txtShare.setVisibility(isMaster ? View.VISIBLE : View.GONE);
            txtFind.setVisibility(state == STATE_CONNECTED ? View.VISIBLE : View.GONE);
            txtKey.setVisibility(state == STATE_UNINITIALIZED ? View.GONE : View.VISIBLE);
            if (txtKey.getVisibility() == View.VISIBLE) {
                String info = "激活钥匙";
                if (state == STATE_CONNECTED) info = "数字钥匙";
                else if (state == STATE_ACTIVATED) info = "连接车辆";
                txtKey.setText(info);
            }
            txtState.setVisibility(View.VISIBLE);
            if (state == STATE_UNINITIALIZED) {
                txtState.setText("数字钥匙初始化失败");
                txtState.setTextColor(Color.RED);
            } else {
                txtState.setText(state == STATE_CONNECTED ? "已连接" : "未连接");
                txtState.setTextColor(Color.BLACK);
            }
            txtState.setSelected(state == STATE_CONNECTED);
        });
    }

    private ProgressDialog pd;
    private void showLoading() {
        if (pd == null) {
            pd = ProgressDialog.show(this, null, "数字钥匙初始化");
            pd.setCancelable(true);
        } else {
            if (!pd.isShowing()) pd.show();
        }
    }

    private void dismissLoading() {
        if (pd != null && pd.isShowing()) pd.dismiss();
    }

    private void showMsg(String msg) {
        rootView.post(() -> Snackbar.make(rootView, msg, Snackbar.LENGTH_LONG).show());
    }

    private boolean initFinger;
    private void initFinger() {
        if (!initFinger) {
            initFinger = true;
            KeyManager.initFinger(this);
        }
    }

    private void releaseFinger() {
        if (initFinger) {
            initFinger = false;
            KeyManager.releaseFinger();
        }
    }

    private NormalCallbackWrapper initNormalCBWrapper;
    private StatusCallBackWrapper statusCallBackWrapper;
    private Handler keyInitHandler;
    private void initDigitalKey() {
        if (keyState != STATE_UNINITIALIZED && keyState != STATE_INVALID) return;
        keyState = STATE_INITIALIZING;
        showLoading();
        rootView.post(() -> rootView.post(() -> {
            if (keyInitHandler == null) {
                HandlerThread keyInitThread = new HandlerThread(
                        "keyInitThread", Process.THREAD_PRIORITY_BACKGROUND
                );
                keyInitThread.start();
                keyInitHandler = new Handler(keyInitThread.getLooper());
            }
            if (initNormalCBWrapper == null)
                initNormalCBWrapper = new NormalCallbackWrapper(new KeyManager.NormalCallback() {
                    @Override
                    public void onSuccess() {
                        KeyManager.isMaster(
                                phone,
                                isMaster -> rootView.post(() -> {
                                    txtOwner.setVisibility(View.VISIBLE);
                                    txtOwner.setText(isMaster ? "车主" : "使用者");
                                    MainActivity.this.isMaster = isMaster;
                                    if (statusCallBackWrapper == null)
                                        statusCallBackWrapper = new StatusCallBackWrapper(
                                                status -> onKeyStateChanged(status)
                                        );
                                    KeyManager.getStatus(statusCallBackWrapper);
                                })
                        );
                    }

                    @Override
                    public void onFail(String errorMsg) {
                        onKeyStateChanged(STATE_UNINITIALIZED);
                        showMsg(errorMsg);
                    }
                });

            KeyManager.PHONE = phone;
            KeyManager.USER_ID = KeyManager.PHONE;
            KeyManager.setKeyStatusInterface(this::onKeyStateChanged);

            keyInitHandler.post(() -> {
                initFinger();
                KeyManager.initSDK(getApplicationContext(), initNormalCBWrapper);
            });
        }));
    }

    private void releaseDigitalKey() {
        if (initNormalCBWrapper != null) {
            initNormalCBWrapper.release();
            initNormalCBWrapper = null;
        }
        if (statusCallBackWrapper != null) {
            statusCallBackWrapper.release();
            statusCallBackWrapper = null;
        }
        if (findCarNormalCBWrapper != null) {
            findCarNormalCBWrapper.release();
            findCarNormalCBWrapper = null;
        }
        if (keyState != STATE_INVALID) {
            keyState = STATE_INVALID;
            KeyManager.setKeyStatusInterface(null);
            KeyManager.releaseKey();
        }
        releaseFinger();
        if (keyInitHandler != null) {
            keyInitHandler.removeCallbacksAndMessages(null);
            keyInitHandler.getLooper().quit();
            keyInitHandler = null;
        }
    }
}
